package org.lwjgl.demo.geometries;

/**
 * 简单星空背景类
 *
 * @author zhoudy
 * @date 2025/10/29 22:45
 */
import org.lwjgl.system.MemoryStack;

import java.nio.FloatBuffer;
import java.util.Random;

import static org.lwjgl.opengl.GL30.*;

public class StarField {
    private int vao;
    private int vbo;
    private int starCount;

    public StarField(int starCount) {
        this.starCount = starCount;
        generateStars();
    }

    private void generateStars() {
        Random random = new Random();
        float[] vertices = new float[starCount * 6];

        for (int i = 0; i < starCount; i++) {
            int baseIndex = i * 6;

            // 随机位置
            float radius = 30.0f + random.nextFloat() * 20.0f;
            float theta = random.nextFloat() * (float) Math.PI * 2;
            float phi = random.nextFloat() * (float) Math.PI;

            vertices[baseIndex] = radius * (float) Math.sin(phi) * (float) Math.cos(theta);
            vertices[baseIndex + 1] = radius * (float) Math.sin(phi) * (float) Math.sin(theta);
            vertices[baseIndex + 2] = radius * (float) Math.cos(phi);

            // 随机颜色和亮度（让亮度变化更明显）
            float brightness = 0.5f + random.nextFloat() * 0.5f; // 亮度范围 0.5-1.0
            vertices[baseIndex + 3] = brightness; // R
            vertices[baseIndex + 4] = brightness; // G
            vertices[baseIndex + 5] = brightness + random.nextFloat() * 0.3f; // B (偏蓝)
        }

        setupMesh(vertices);
    }

    private void setupMesh(float[] vertices) {
        vao = glGenVertexArrays();
        vbo = glGenBuffers();

        glBindVertexArray(vao);

        MemoryStack stack = MemoryStack.stackPush();
        try {
            FloatBuffer vertexBuffer = stack.mallocFloat(vertices.length);
            vertexBuffer.put(vertices).flip();

            glBindBuffer(GL_ARRAY_BUFFER, vbo);
            glBufferData(GL_ARRAY_BUFFER, vertexBuffer, GL_STATIC_DRAW);

            // 位置属性
            glVertexAttribPointer(0, 3, GL_FLOAT, false, 6 * Float.BYTES, 0);
            glEnableVertexAttribArray(0);

            // 颜色属性
            glVertexAttribPointer(1, 3, GL_FLOAT, false, 6 * Float.BYTES, 3 * Float.BYTES);
            glEnableVertexAttribArray(1);

        } finally {
            stack.pop();
        }

        glBindVertexArray(0);
    }

    public void render() {
        glBindVertexArray(vao);
        glDrawArrays(GL_POINTS, 0, starCount); // 使用点图元渲染星星
        glBindVertexArray(0);
    }

    public void cleanup() {
        glDeleteVertexArrays(vao);
        glDeleteBuffers(vbo);
    }
}
